#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tpf_dataflow_base.py 
@version:
@time: 2022/01/11 
"""
from TapClientCore.T01_init_conf.v2_init.init_config import MFA, config, collection_name
from TapClientCore.T05_TM_feature.v1.TMF02_dataflow.tmf_dataflow import TMFV1DataFlow
from TapException.TM import *
from TapUtil.logfunc.logger import logger


class TPFDataFlowBase:
    """
    通过name和serve字段可以确定一个记录
    """
    TMF = TMFV1DataFlow()
    serve = TMF.v1tm.serve
    user = TMF.v1tm.user

    def dataflow_insert_mongodb(self, kwargs):
        MFA.insert_one(collection_name,
                       {
                           'serve': self.serve,
                           'user': self.user,
                           **kwargs
                       })

    def dataflow_delete_mongodb(self, kwargs):
        name = kwargs.get('name')
        MFA.delete_one(collection_name,
                       {
                           'name': name,
                           'user': self.user,
                           'serve': self.serve
                       })

    def dataflow_update_mongodb(self, kwargs):
        name = kwargs.get('name')
        dataflow_id = kwargs.get('dataflow_id')
        return MFA.update(collection_name,
                          {'name': name, 'user': self.user, 'serve': self.serve},
                          {'$set': {**kwargs}})

    def dataflow_query_mongodb(self, kwargs):
        """
        通过名字查询任务
        :param kwargs:
        :return:
        """
        name = kwargs.get('name')
        query_result = MFA.query(collection_name,
                                 {
                                     'name': name,
                                     'user': self.user,
                                     'serve': self.serve
                                 })
        if query_result:
            return query_result[0]
        return query_result

    def delete_all_record_data_source(self):
        result = MFA.query(collection_name,
                           {
                               'serve': self.serve,
                               'user': self.user,
                           })
        for i in result:
            delete_response = None
            try:
                self.TMF.stopping_and_wait_to_paused(i.get('name'))
                delete_response = self.TMF.delete_dataflow_by_name(i.get('name'))
            except DataFlowError as e:
                delete_response = self.TMF.delete_dataflow_by_name(i.get('name'))
            except DataFlowRemoveFail as e:
                logger.fatal(e)
            MFA.delete_one(collection_name,
                           {
                               'serve': self.serve,
                               'user': self.user,
                               'name': i.get('name')
                           })
